// pages/stockDetail/stockDetail.js
const stockAPI = require('../../utils/stockApi');

Page({
  /**
   * 页面的初始数据
   */
  data: {
    stockCode: '',
    stockName: '',
    stockData: {},
    loading: true,
    isFavorite: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const { code, name } = options;
    this.setData({
      stockCode: code,
      stockName: name
    });
    
    // 设置导航栏标题
    wx.setNavigationBarTitle({
      title: name || '股票详情'
    });
    
    this.loadStockDetail();
    this.checkFavoriteStatus();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // 页面显示时刷新数据
    if (this.data.stockCode) {
      this.refreshStockData();
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉刷新
   */
  onPullDownRefresh() {
    this.refreshStockData().then(() => {
      wx.stopPullDownRefresh();
    });
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      title: `${this.data.stockName}(${this.data.stockCode}) - 股票详情`,
      path: `/pages/stockDetail/stockDetail?code=${this.data.stockCode}&name=${this.data.stockName}`
    };
  },

  /**
   * 加载股票详情数据
   */
  async loadStockDetail() {
    try {
      this.setData({ loading: true });
      
      const result = await stockAPI.getStockData(this.data.stockCode);
      
      if (result.success) {
        this.setData({
          stockData: result.data,
          loading: false
        });
      } else {
        throw new Error(result.error);
      }
    } catch (error) {
      console.error('加载股票详情失败:', error);
      this.setData({ loading: false });
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      });
    }
  },

  /**
   * 刷新股票数据
   */
  async refreshStockData() {
    try {
      const result = await stockAPI.getStockData(this.data.stockCode);
      
      if (result.success) {
        this.setData({
          stockData: result.data
        });
      }
    } catch (error) {
      console.error('刷新股票数据失败:', error);
    }
  },

  /**
   * 检查自选状态
   */
  checkFavoriteStatus() {
    // 从本地存储获取自选列表
    const favorites = wx.getStorageSync('favoriteStocks') || [];
    const isFavorite = favorites.some(item => item.code === this.data.stockCode);
    this.setData({ isFavorite });
  },

  /**
   * 买入股票
   */
  buyStock() {
    wx.switchTab({
      url: '/pages/simulate/simulate'
    });
  },

  /**
   * 卖出股票
   */
  sellStock() {
    wx.switchTab({
      url: '/pages/simulate/simulate'
    });
  },

  /**
   * 切换自选状态
   */
  toggleFavorite() {
    const favorites = wx.getStorageSync('favoriteStocks') || [];
    const stockInfo = {
      code: this.data.stockCode,
      name: this.data.stockName
    };

    if (this.data.isFavorite) {
      // 移除自选
      const newFavorites = favorites.filter(item => item.code !== this.data.stockCode);
      wx.setStorageSync('favoriteStocks', newFavorites);
      this.setData({ isFavorite: false });
      wx.showToast({
        title: '已取消自选',
        icon: 'success'
      });
    } else {
      // 添加自选
      favorites.push(stockInfo);
      wx.setStorageSync('favoriteStocks', favorites);
      this.setData({ isFavorite: true });
      wx.showToast({
        title: '已加入自选',
        icon: 'success'
      });
    }
  }
});
